
(function($) {

  $.fn.serializeObject = function()
  {
     var o = {};
     var a = this.serializeArray();
     $.each(a, function() {
         if (o[this.name]) {
             if (!o[this.name].push) {
                 o[this.name] = [o[this.name]];
             }
             o[this.name].push(this.value || '');
         } else {
             o[this.name] = this.value || '';
         }
     });
     return o;
  };
  $.fn.clickToggle = function(func1, func2) {
      var funcs = [func1, func2];
      this.data('toggleclicked', 0);
      this.click(function() {
          var data = $(this).data();
          var tc = data.toggleclicked;
          $.proxy(funcs[tc], this)();
          data.toggleclicked = (tc + 1) % 2;
      });
      return this;
  };
}(jQuery));

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    var expires = "";
    if(exdays != "") {
      d.setTime(d.getTime() + (exdays*24*60*60*1000));
      expires = "; expires="+d.toUTCString();
  }
    document.cookie = cname + "=" + cvalue + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie() {
    var user = getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
        user = prompt("Please enter your name:", "");
        if (user != "" && user != null) {
            setCookie("username", user, 365);
        }
    }
}
function getLocation(successFunction)
{
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
  }  
}
function successFunction(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    setCookie('Latitude',lat,'');
    setCookie('Longitude',lng,'');
    console.log('Latitude: '+lat);
    console.log('Longitude: '+lng);
    $('<div>Latitude: '+lat+'                    Longitude: '+lng+'</div>').insertAfter('#footer');
    //codeLatLng(lat, lng);
}

function errorFunction(){
    console.log("Shaphira khong the lay duoc vi tri cua ban");
}

function codeLatLng(lat, lng) {

  var geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        console.log(results);
      //formatted address
      var _results = results[1];
      setCookie('Address',_results.formatted_address,'');
      /*//tìm tên nước
      for (var i = 0 ; i < _results.address_components.length; i++) {
        for (var b = 0 ; b < _results.address_components[i].types.length; b++) {
        //there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
          if (_results.address_components[i].types[b] == "administrative_area_level_1") {
              
              city= _results.address_components[i];
              break;
          }
        }
      }
      //city data
      alert(city.short_name + " " + city.long_name)*/
      } else {
        alert("No results found");
      }
    } else {
      alert("Geocoder failed due to: " + status);
    }
  });
}

function get_data () {
  var col = 1;
  // row : x
  var row = 1;
  // Item
  var item = 0;
  var text= '<br>';
  function print_data (data) {
    
    for( var i = 0 ; i < data[1].length ; i++){
      var className = '.dashboard-col-' + col ;
      item++;
      
      $( className).append(' <div class="dashboard" data-group="'+ data[0]+'" rel="' + item + '"> <div class="block"> danh muc : <b>' + data[0] + '</b><hr> <br>Row : '+ row + ' Col : '+ col + ' item : '+ item + text+'<br> Gia tri : ' +data[1][i]+'</div></div>');
      text+= '<br>';
      if (col < 3) { col++; }
      else { col = 1 ; row++ ;}
    }
  }

  $(document).ready(function() {
    // Number data : z
    // Number data : z
    var test = ['test',[1,123,234124,124124324,234234]];
    var profile =['profile',[11,12,13,14,15,16,17,18]];
    var photo =['photo',['Khong ',' biet',' co',' duoc', ' khong']];
    var sothich =['sothich',[' cu', ' thu', ' truoc', ' da', ' tinh' , ' sau']];

    var data = [];
    data.push(test);
    data.push(profile);
    data.push(photo);
    data.push(sothich);

    var select = "profile";
    for(var i = 0; i < data.length; i++)
    {
      if(data[i][1].length > 0){
        switch (data[i][0]) {
          case 0 :
            console.log("khong co j het");
            break;
            case select:
              print_data(data[i]);
              data[i] = [[],[]];
              for(var j = 0 ; j < data.length; j ++){
                print_data(data[j]);
              }
                break;
            default:
              break;
        }
      }
    }

    
    $('.btn_change_html').click( function () {
      $('.dashboard-col').
      col = 1;
      row = 1;
      var group = $(this).data('group');
      var div = $('.dashboard[data-group="'+group+'"]');
      $('.dashboard[data-group="'+group+'"]').remove();
      var column;
      // Su dung thuat toan sui bot sap sep cac thanh phan trong mang theo thu tu
      for(var i = 0 ; i < div.length; i++) {
        if(i != div.length){
          for(var j = i ; j < div.length; j++){
            var Num_a = $(div[i]).attr('rel');
            var Num_b = $(div[j]).attr('rel');
            if( parseInt(Num_a) > parseInt(Num_b) ){
              var a = div[i];
              div[i] = div[j];
              div[j] = a;
            }
          }
        }
      }
      // vong lap for sap sep lai thuat toan tren html
      for( var i = 0  ; i < div.length  ; i++){
        var className = '.dashboard-col-' + col ;
        column   = $(className)[0];
        var node = column.childNodes[row];
        column.insertBefore(div[i],node);

        if (col < 3) { col++; }
        else { col = 1 ; row++ ;}
      }

    });
  });
}